/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package util;

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.sql.Date;
import java.text.SimpleDateFormat;

/**
 * Ghi Ngoại lệ hoặc message ra Log File !
 */
public class LogUtil {

    public static String getCurrentTime() {
        Date todayD = new Date(System.currentTimeMillis());
        SimpleDateFormat dayFormat = new SimpleDateFormat("yyyy-MM-dd @HH:mm:ss.S");
        return dayFormat.format(todayD.getTime());
    }
    public static void doLog(Object o) {
        String nowDateTime = getCurrentTime();
        try {
            if (o instanceof Throwable) {
                Throwable t = (Throwable) o;
                StringWriter sw = new StringWriter();
                PrintWriter pw = new PrintWriter(sw);
                StringBuffer bf = new StringBuffer("[");
                bf.append(nowDateTime);
                bf.append("]");
                bf.append("<< EXCEPTION >>");
                bf.append(":\"");
                bf.append(sw.toString().trim());
                bf.append("\".");
//                String print = "[" + nowDateTime + "]" + "<< EXCEPTION >>" + ":\"" + sw.toString().trim() + "\".";
                System.err.println(bf);
                writeFile(bf.toString());
            } else if (o instanceof String) {
                StringBuffer bf = new StringBuffer("[");
                bf.append(nowDateTime);
                bf.append("]");
                bf.append("<< MESSAGE >>:\"");
                bf.append(((String)o).toUpperCase() );
                bf.append("\";");
//              System.out.println("--- Đã ghi vào SERVICE_LOG !---");
                writeFile(bf.toString());
            } else {
                String print = "[" + nowDateTime + "]" + "<< UNTITLED >>" + ":\"" + o.getClass().getName()+ "\" : " + o.toString() + "!";
                writeFile(print);
            }
        } catch (Exception e) {
            doLog(e);
        }
    }

    private synchronized  static void writeFile(String str) {
        FileWriter fwriter = null;
        try {
            fwriter = new FileWriter("SERVICE_LOG.txt", true);
            BufferedWriter writer = new BufferedWriter(fwriter);
            writer.write(str);
            writer.write("\t");
            writer.newLine();
            writer.close();
        } catch (IOException ex) {
            doLog(ex);
        } finally {
            try {
                if (fwriter != null) {
                    fwriter.close();
                }
            } catch (IOException ex) {
                doLog(ex);
            }
        }
    }
}
